package com.education.ai.service.impl;

import com.education.ai.entity.Teacher;
import com.education.ai.dao.TeacherDao;
import com.education.ai.service.TeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 教师服务实现类
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public List<Teacher> getAllTeachers() {
        return teacherDao.findAll();
    }

    @Override
    public Optional<Teacher> getTeacherById(Long id) {
        return teacherDao.findById(id);
    }

    @Override
    public Optional<Teacher> getTeacherByTeacherId(String teacherId) {
        return teacherDao.findByTeacherId(teacherId);
    }

    @Override
    @Transactional
    public Teacher saveTeacher(Teacher teacher) {
        return teacherDao.save(teacher);
    }

    @Override
    @Transactional
    public void deleteTeacher(Long id) {
        teacherDao.deleteById(id);
    }

    @Override
    public List<Teacher> searchTeachersByName(String name) {
        return teacherDao.findByNameContaining(name);
    }

    @Override
    public List<Teacher> getTeachersBySubject(String subject) {
        return teacherDao.findBySubject(subject);
    }

    @Override
    public List<Teacher> searchTeachersBySubjectAndName(String subject, String name) {
        return teacherDao.findBySubjectAndNameContaining(subject, name);
    }

    @Override
    public boolean isTeacherIdExists(String teacherId) {
        return teacherDao.existsByTeacherId(teacherId);
    }
    
    @Override
    @Transactional
    public boolean updatePassword(String teacherId, String currentPassword, String newPassword) {
        logger.info("尝试更新教师 {} 的密码", teacherId);
        
        // 根据教师工号查询教师信息
        Optional<Teacher> optionalTeacher = teacherDao.findByTeacherId(teacherId);
        if (!optionalTeacher.isPresent()) {
            logger.error("更新密码失败：教师ID {} 不存在", teacherId);
            return false;
        }
        
        Teacher teacher = optionalTeacher.get();
        
        // 验证当前密码是否正确 - 使用简单比较而不是密码编码器
        if (!currentPassword.equals(teacher.getPassword())) {
            logger.warn("更新密码失败：当前密码不正确，教师ID: {}", teacherId);
            return false;
        }
        
        // 更新密码 - 直接使用明文密码
        teacher.setPassword(newPassword);
        teacherDao.update(teacher);  // 使用update方法替代save方法
        
        logger.info("成功更新教师 {} 的密码", teacherId);
        return true;
    }

    @Override
    public String getMaxTeacherId() {
        return teacherDao.getMaxTeacherId();
    }
} 